package 树与图.字典树;

import java.util.Stack;

/**
 * 226. 翻转二叉树
 * 给你一棵二叉树的根节点 root ，翻转这棵二叉树，并返回其根节点。
 *
 * 思路： 使用递归翻转
 * 将每一层的左右子树交换，然后递归调用
 */
public class L_226 {

    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return null;
        }
        if(root.left == null && root.right == null){
            return root;
        }
        // 将每一层的左右子树交换
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        // 然后递归调用左右子树进行交换
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
    public TreeNode invertTree1(TreeNode root) {
        if (root == null){
            return root;
        }
        // 使用迭代
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode current = stack.pop();
            // 交换该节点的左右子树
            TreeNode temp = current.left;
            current.left = current.right;
            current.right = temp;
            if (current.left != null){
                stack.push(current.left);
            }
            if (current.right != null){
                stack.push(current.right);
            }
        }
        return root;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
